package com.bookocean.infrastructure.persistence.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bookocean.controller.dto.CloudHanPostDto;
import com.bookocean.domain.repository.BookQuoteRepository;
import com.bookocean.infrastructure.persistence.mapper.BookMapper;
import com.bookocean.infrastructure.persistence.mapper.BookQuoteMapper;
import com.bookocean.infrastructure.persistence.mapper.UserInfoMapper;
import com.bookocean.infrastructure.persistence.po.BookPO;
import com.bookocean.infrastructure.persistence.po.BookQuotePO;
import com.bookocean.infrastructure.persistence.po.UserInfoPO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 书摘仓储实现类
 * 
 * @author BookOcean
 * @since 2024-01-01
 */
@Slf4j
@Repository
@RequiredArgsConstructor
public class BookQuoteRepositoryImpl implements BookQuoteRepository {

    private final BookQuoteMapper bookQuoteMapper;
    private final BookMapper bookMapper;
    private final UserInfoMapper userInfoMapper;

    @Override
    public List<CloudHanPostDto> getHotPosts(Integer page, Integer pageSize, Integer categoryId) {
        try {
            // 构建查询条件
            LambdaQueryWrapper<BookQuotePO> queryWrapper = new LambdaQueryWrapper<>();
            if (categoryId != null) {
                // 修复：将数字类型的categoryId转换为字符串进行查询
                queryWrapper.eq(BookQuotePO::getType, String.valueOf(categoryId));
            }
            
            // 按创建时间排序（热门排序在业务层处理）
            queryWrapper.orderByDesc(BookQuotePO::getCreatedAt);
            
            // 分页查询
            Page<BookQuotePO> pageParam = new Page<>(page, pageSize);
            Page<BookQuotePO> result = bookQuoteMapper.selectPage(pageParam, queryWrapper);
            
            return result.getRecords().stream()
                    .map(this::convertToDto)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取热门书摘失败: {}", e.getMessage(), e);
            return Collections.emptyList();
        }
    }

    @Override
    public Long getHotPostsCount(Integer categoryId) {
        try {
            LambdaQueryWrapper<BookQuotePO> queryWrapper = new LambdaQueryWrapper<>();
            if (categoryId != null) {
                // 修复：将数字类型的categoryId转换为字符串进行查询
                queryWrapper.eq(BookQuotePO::getType, String.valueOf(categoryId));
            }
            return bookQuoteMapper.selectCount(queryWrapper);
        } catch (Exception e) {
            log.error("获取热门书摘总数失败: {}", e.getMessage(), e);
            return 0L;
        }
    }

    @Override
    public List<CloudHanPostDto> getLatestPosts(Integer page, Integer pageSize, Integer categoryId) {
        try {
            LambdaQueryWrapper<BookQuotePO> queryWrapper = new LambdaQueryWrapper<>();
            if (categoryId != null) {
                // 修复：将数字类型的categoryId转换为字符串进行查询
                queryWrapper.eq(BookQuotePO::getType, String.valueOf(categoryId));
            }
            
            // 按创建时间倒序
            queryWrapper.orderByDesc(BookQuotePO::getCreatedAt);
            
            // 分页查询
            Page<BookQuotePO> pageParam = new Page<>(page, pageSize);
            Page<BookQuotePO> result = bookQuoteMapper.selectPage(pageParam, queryWrapper);
            
            return result.getRecords().stream()
                    .map(this::convertToDto)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取最新书摘失败: {}", e.getMessage(), e);
            return Collections.emptyList();
        }
    }

    @Override
    public Long getLatestPostsCount(Integer categoryId) {
        try {
            LambdaQueryWrapper<BookQuotePO> queryWrapper = new LambdaQueryWrapper<>();
            if (categoryId != null) {
                // 修复：将数字类型的categoryId转换为字符串进行查询
                queryWrapper.eq(BookQuotePO::getType, String.valueOf(categoryId));
            }
            return bookQuoteMapper.selectCount(queryWrapper);
        } catch (Exception e) {
            log.error("获取最新书摘总数失败: {}", e.getMessage(), e);
            return 0L;
        }
    }

    @Override
    public List<CloudHanPostDto> searchPosts(String keyword, Integer page, Integer pageSize, Integer categoryId) {
        try {
            LambdaQueryWrapper<BookQuotePO> queryWrapper = new LambdaQueryWrapper<>();
            
            // 分类筛选
            if (categoryId != null) {
                // 修复：将数字类型的categoryId转换为字符串进行查询
                queryWrapper.eq(BookQuotePO::getType, String.valueOf(categoryId));
            }
            
            // 关键词搜索（书摘内容、用户感想）
            if (keyword != null && !keyword.trim().isEmpty()) {
                queryWrapper.and(wrapper -> wrapper
                    .like(BookQuotePO::getContent, keyword.trim())
                    .or()
                    .like(BookQuotePO::getUserFeel, keyword.trim())
                );
            }
            
            // 按创建时间倒序
            queryWrapper.orderByDesc(BookQuotePO::getCreatedAt);
            
            // 分页查询
            Page<BookQuotePO> pageParam = new Page<>(page, pageSize);
            Page<BookQuotePO> result = bookQuoteMapper.selectPage(pageParam, queryWrapper);
            
            return result.getRecords().stream()
                    .map(this::convertToDto)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("搜索书摘失败: {}", e.getMessage(), e);
            return Collections.emptyList();
        }
    }

    @Override
    public Long searchPostsCount(String keyword, Integer categoryId) {
        try {
            LambdaQueryWrapper<BookQuotePO> queryWrapper = new LambdaQueryWrapper<>();
            
            // 分类筛选
            if (categoryId != null) {
                // 修复：将数字类型的categoryId转换为字符串进行查询
                queryWrapper.eq(BookQuotePO::getType, String.valueOf(categoryId));
            }
            
            // 关键词搜索
            if (keyword != null && !keyword.trim().isEmpty()) {
                queryWrapper.and(wrapper -> wrapper
                    .like(BookQuotePO::getContent, keyword.trim())
                    .or()
                    .like(BookQuotePO::getUserFeel, keyword.trim())
                );
            }
            
            return bookQuoteMapper.selectCount(queryWrapper);
        } catch (Exception e) {
            log.error("获取搜索结果总数失败: {}", e.getMessage(), e);
            return 0L;
        }
    }

    /**
     * 转换PO到DTO
     */
    private CloudHanPostDto convertToDto(BookQuotePO po) {
        CloudHanPostDto dto = new CloudHanPostDto();
        dto.setId(po.getQuoteId());
        dto.setContent(po.getContent());
        dto.setUserFeel(po.getUserFeel());
        dto.setCreatedAt(po.getCreatedAt());
        
        // 关联查询书籍信息
        CloudHanPostDto.BookInfo bookInfo = new CloudHanPostDto.BookInfo();
        bookInfo.setId(po.getBookId());
        try {
            BookPO book = bookMapper.selectById(po.getBookId());
            if (book != null) {
                bookInfo.setTitle(book.getTitle());
                bookInfo.setAuthor(book.getAuthor());
                bookInfo.setCoverUrl(book.getCoverUrl());
                if (book.getCategory() != null) {
                    try {
                        bookInfo.setCategory(Integer.valueOf(book.getCategory()));
                    } catch (NumberFormatException e) {
                        bookInfo.setCategory(1); // 默认分类
                    }
                } else {
                    bookInfo.setCategory(po.getType() != null ? Integer.valueOf(po.getType()) : 1);
                }
            } else {
                // 设置默认书籍信息
                bookInfo.setTitle("未知书籍");
                bookInfo.setAuthor("佚名");
                bookInfo.setCoverUrl("/static/home/card0.png");
                bookInfo.setCategory(po.getType() != null ? Integer.valueOf(po.getType()) : 1);
            }
        } catch (Exception e) {
            log.warn("查询书籍信息失败，bookId: {}, error: {}", po.getBookId(), e.getMessage());
            // 设置默认书籍信息
            bookInfo.setTitle("未知书籍");
            bookInfo.setAuthor("佚名");
            bookInfo.setCoverUrl("/static/home/card0.png");
            bookInfo.setCategory(po.getType() != null ? Integer.valueOf(po.getType()) : 1);
        }
        dto.setBook(bookInfo);
        
        // 关联查询用户信息
        CloudHanPostDto.UserInfo userInfo = new CloudHanPostDto.UserInfo();
        userInfo.setId(po.getUserId());
        try {
            UserInfoPO user = userInfoMapper.selectById(po.getUserId());
            if (user != null) {
                userInfo.setNickname(user.getNickName());
                userInfo.setAvatar(user.getAvatarUrl());
                userInfo.setTitle(user.getTitle());
            } else {
                // 设置默认用户信息
                userInfo.setNickname("匿名用户");
                userInfo.setAvatar("/static/default-avatar.png");
                userInfo.setTitle("读者");
            }
        } catch (Exception e) {
            log.warn("查询用户信息失败，userId: {}, error: {}", po.getUserId(), e.getMessage());
            // 设置默认用户信息
            userInfo.setNickname("匿名用户");
            userInfo.setAvatar("/static/default-avatar.png");
            userInfo.setTitle("读者");
        }
        dto.setUser(userInfo);
        
        return dto;
    }
}
